package cn.com.anypay.manager.controller.sdk;

import cn.com.anypay.manager.common.response.ApiResponse;
import cn.com.anypay.manager.service.SmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/sms")
public class SmsController {
    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private SmsService smsService;

    @GetMapping("/config")
    public ApiResponse<Map<String, Object>> getConfig(@RequestParam(required = false) String provider) {
        logger.info("开始获取短信配置，provider: {}", provider);
        Map<String, Object> config;
        if (provider != null) {
            config = smsService.getConfigByProvider(provider);
        } else {
            config = smsService.getCurrentConfig();
        }
        logger.info("获取短信配置成功: {}", config);
        return ApiResponse.success(config);
    }

    @PostMapping("/switch")
    public ApiResponse<String> switchProvider(@RequestBody Map<String, Object> config) {
        logger.info("开始切换短信服务商，配置参数: {}", config);
        String result = smsService.switchProvider(config);
        logger.info("切换短信服务商成功: {}", result);
        return ApiResponse.success("切换短信服务商成功", result);
    }

    @PostMapping("/send")
    public ApiResponse<Map<String, Object>> send(@RequestBody Map<String, String> request) {
        logger.info("收到发送短信请求，参数: {}", request);
        // 检查服务商配置
        Map<String, Object> currentConfig = smsService.getCurrentConfig();
        if (currentConfig == null || currentConfig.isEmpty()) {
            logger.warn("短信服务商未配置");
            return ApiResponse.fail("请先配置短信服务商");
        }

        String phone = request.get("phone");
        String templateParams = request.get("templateParams");

        logger.info("解析请求参数 - 手机号: {}, 模板参数: {}", phone, templateParams);

        if (phone == null || phone.isEmpty()) {
            logger.warn("手机号为空");
            return ApiResponse.fail("手机号不能为空");
        }

        if (templateParams == null || templateParams.isEmpty()) {
            logger.warn("模板参数为空");
            return ApiResponse.fail("模板参数不能为空");
        }

        logger.info("开始发送短信 - 手机号: {}, 模板参数: {}", phone, templateParams);
        Map<String, Object> result = smsService.sendSms(phone, templateParams);
        logger.info("短信发送成功，结果: {}", result);
        return ApiResponse.success(result);
    }
}
